package com.vchello.controller.user;

import java.io.IOException;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONException;
import com.baomidou.mybatisplus.plugins.Page;
import com.vchello.bean.bind.UserInfoData;
import com.vchello.bean.file.Folder;
import com.vchello.bean.security.Role;
import com.vchello.bean.security.UserRole;
import com.vchello.bean.user.Invitation;
import com.vchello.bean.user.User;
import com.vchello.bean.user.UserProgress;
import com.vchello.controller.BaseController;
import com.vchello.controller.constants.SubjectAttrConstants;
import com.vchello.service.file.FolderService;
import com.vchello.service.project.ProjectService;
import com.vchello.service.security.RoleService;
import com.vchello.service.security.UserRoleService;
import com.vchello.service.user.InvitationService;
import com.vchello.service.user.UserService;
import com.vchello.util.RandomUtil;
import com.vchello.util.SendEmail;
import com.vchello.util.SmsUtil;
import com.vchello.util.ToolUtil;
import com.vchello.util.UploadFileHelper;
import com.vchello.util.Utility;



/**
 * 
 * @author power
 *
 */
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {

	private static final String REDIRECT_LOGIN = "redirect:/login";
	private static final int STATUS = 1;

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private InvitationService invitationService;
	@Autowired
	private FolderService folderService;
	@Autowired
	private ProjectService projectService;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model, Page<UserRole> page) {
		User user = getUser();
		if(null == user) {
			return REDIRECT_LOGIN;
		}
		page = userRoleService.findUserRoleByFatherId(page, user, 0);
		List<Role> roleList = roleService.findRoleByUserId(user.getId());
		model.addAttribute("roleList", roleList).addAttribute("page", page).addAttribute("roleId", 0);
		return "user/user-manage";

	}
	
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public String list(Page<UserRole> page, User user, Model model, int roleId) {
		page = userRoleService.findUserRoleByFatherId(page, user, roleId);
		model.addAttribute("page", page).addAttribute("roleId", roleId);
		return "user/query/userQuery";
		
	}

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register(Model model) {
		model.addAttribute("user", new User());
		return "login";

	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public void register(Model model, User user, int securityCode, @RequestParam(value = "code", required = false) String code) {
		int phoneCode = Integer.valueOf(session.getAttribute(SubjectAttrConstants.SESSION_PHONE_CODE).toString());
		if (phoneCode != securityCode) {
			error("手机验证码错误");
			return;
		}
		if (null == user) {
			error("填写的资料为空");
			return;
		}
		user.setPassword(Utility.md5md5(user.getPassword()));
		user.setStatus(STATUS);
		user.setCreateTime(Utility.getSimpleFormatedDayNow());
		boolean isTrue = userService.insert(user);
		if (!isTrue) {
			error("注册失败");
			return;
		}
		
		saveInvitation(code, user.getId());//邀请成员注册填写邀请码
		if(user.getType() == 1) {
			roleService.saveRole(new Role("合伙人", user.getId()));    //帮用户创建默认的城市合伙人角色
		}
		folderService.saveFolder(new Folder("我的文件", user.getId(), 0, 0, Utility.getSimpleFormatedDayNow()));  //帮用户创建默认文件夹(不能删除)
		folderService.saveFolder(new Folder("其他文件", user.getId(), 0, 0, Utility.getSimpleFormatedDayNow()));
		folderService.saveFolder(new Folder("尽调文件", user.getId(), 0, 0, Utility.getSimpleFormatedDayNow()));
		projectService.saveOrUpdateProgress(new UserProgress("新收到", projectService.queryProgressSort(user.getId()), (long)user.getId(), 1));//为用户创建默认进度“新收到”
		success("注册成功");

	}
	
	@ResponseBody
	@RequestMapping(value = "/updateUserRole/{userId}", method = RequestMethod.POST)
	public void updateUserRole(@PathVariable int userId) throws JSONException, IOException{
		UserRole userRole = userRoleService.findUserRole(userId);
		success(userRole);
		
	}
	
	@RequestMapping(value = "/findPassword", method = RequestMethod.GET)
	public String findPassword(Model model){
		return "user/findPassword";
		
	}
	
	@RequestMapping(value = "/findPassword", method = RequestMethod.POST)
	public void inputPassword(Model model, int code, String phone) {
		Integer captcha = Integer.valueOf(session.getAttribute(SubjectAttrConstants.SESSION_PHONE_CODE).toString());
		if(captcha != code){
			error("验证码错误");
			return;
		}
		session.setAttribute(SubjectAttrConstants.PHONE, phone);
		
		success(phone);
	}
	
	@RequestMapping(value = "/updatePassword", method = RequestMethod.GET)
	public String updatePassword(Model model){
		return "user/updatePassword";
	}
	
	@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
	public void updatePassword(String phone, String confirmPassword){
		String sessionPhone = (String) session.getAttribute(SubjectAttrConstants.PHONE);
		if(!sessionPhone.equals(phone)) {
			error("验证的手机号码错误");
		}
		User user  = userService.findUserByPhone(phone);
		if(null == user) {
			error("手机号码未注册");
			return;
		}
		user.setPassword(Utility.md5(confirmPassword));
		boolean isTrue = userService.insertOrUpdate(user);
		if(isTrue) {
			session.removeAttribute(SubjectAttrConstants.PHONE);
			SecurityUtils.getSubject().logout();
			success("找回密码成功");
			return;
		}
		error("找回密码失败,请重新操作");
	}
	
	@RequestMapping(value = "/accountSettings", method = RequestMethod.GET)
	public String accountSettings(){
		User user = getUser();
		if(null == user) {
			return REDIRECT_LOGIN;
		}
		return "user/setting";
		
	}
	
	@RequestMapping(value = "/accountSettings", method = RequestMethod.POST)
	public void accountSettings(UserInfoData userInfoData) throws IOException{
		User user = getUser();
		if(null == user) {
			error("用户未登录");
			return;
		}
		switch (userInfoData.getType()) {
		case 1: //头像
			String logo = UploadFileHelper.isFileExists(userInfoData.getLogo(), request);
			user.setLogo(logo);
			break;
		case 2://用户名
			user.setUserName(userInfoData.getUserName());
			break;
		case 3: //修改密码
			if(!user.getPassword().equals(Utility.md5md5(userInfoData.getOldPassword()))){
				error("旧密码不正确");
				return;
			}
			if(!userInfoData.getNewPassword().equals(userInfoData.getConfirmPassword())) {
				error("两次密码不一致");
				return;
			}
			user.setPassword(Utility.md5md5(userInfoData.getConfirmPassword()));
			break;
		case 4:  //绑定邮箱
			String sessionEmailCode = (String) session.getAttribute(SubjectAttrConstants.SESSION_EMAIL_CODE);
			if (!sessionEmailCode.equals(userInfoData.getEmailCode().toUpperCase())) {
				error("邮箱验证码错误");
				return;
			}
			user.setEmail(userInfoData.getEmail());
			break;
		case 5:  //绑定手机
			String sessionCode = (String) session.getAttribute(SubjectAttrConstants.SESSION_PHONE_CODE);
			if (!sessionCode.equals(userInfoData.getPhoneCode().toUpperCase())) {
				error("手机验证码错误");
				return;
			}
			user.setPhone(userInfoData.getPhone());
			break;
		case 6:  //绑定微信
			break;
		default:
			break;
		}
		boolean isTrue = userService.insertOrUpdate(user);
		if(isTrue) {
			session.setAttribute(SubjectAttrConstants.USER_AWARE_CONSTANT, user);
			success("修改成功");
		}
		success("修改失败");
	}
	
	/**
	 * 注册发送验证码
	 * @param code
	 * @param phone
	 */
	@ResponseBody
	@RequestMapping(value = "/sendCaptcha", method = RequestMethod.POST)
	public void sendCaptcha(String code, String phone) {
		try {
			checkPhone(phone);

			/**
			 * 图形验证码判断
			 */
			String captchaCode = (String) session.getAttribute(SubjectAttrConstants.SESSION_SECURITY_CODE);
			if (code != null && !captchaCode.equals(code.toUpperCase())) {
				error("图形验证码不正确！");
				return;
			}

			User user  = userService.findUserByPhone(phone);
			if (user != null) {
				error("手机号码已存在");
				return;
			}

			int num = RandomUtil.randomNum();
			String msg = "验证码" + num + ",您正在使用微投网注册，需要进行校验！";
			String returnCode = SmsUtil.batchSend(phone, msg, true, null, null);
//			 String returnCode = "20110725160412,0";
			session.setAttribute(SubjectAttrConstants.SESSION_PHONE_CODE, num);
			success(num, Utility.getReturnCode(returnCode));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 找回密码发送验证码
	 * @param code
	 * @param phone
	 */
	@ResponseBody
	@RequestMapping(value = "/sendCaptchaByPasswrod", method = RequestMethod.POST)
	public void sendCaptchaByPasswrod(String securityCode, String phone) {
		try {
			checkPhone(phone);
			
			/**
			 * 图形验证码判断
			 */
			String captchaCode = (String) session.getAttribute(SubjectAttrConstants.SESSION_SECURITY_CODE);
			if (securityCode != null && !captchaCode.equals(securityCode.toUpperCase())) {
				error("图形验证码不正确！");
				return;
			}
			
			User user  = userService.findUserByPhone(phone);
			if (user == null) {
				error("手机号码不存在,或者未注册");
				return;
			}
			
			
			int num = RandomUtil.randomNum();
			String msg = "验证码" + num + ",您正在使用微投网找回密码，需要进行校验！";
			String returnCode = SmsUtil.batchSend(phone, msg, true, null, null);
//			 String returnCode = "20110725160412,0";
			session.setAttribute(SubjectAttrConstants.SESSION_PHONE_CODE, num);
			success(num, Utility.getReturnCode(returnCode));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 手机绑定发送验证码
	 * @param code
	 * @param phone
	 */
	@ResponseBody
	@RequestMapping(value = "/sendCaptchaByPhone", method = RequestMethod.POST)
	public void sendCaptchaByPhone(String phone) {
		try {
			checkPhone(phone);
			User user  = userService.findUserByPhone(phone);
			if (user == null) {
				error("手机号码不存在,或者未注册");
				return;
			}
			
			int num = RandomUtil.randomNum();
			String msg = "验证码" + num + ",您正在使用微投网修改手机，需要进行校验！";
			String returnCode = SmsUtil.batchSend(phone, msg, true, null, null);
//			String returnCode = "20110725160412,0";
			session.setAttribute(SubjectAttrConstants.SESSION_PHONE_CODE, num);
			success(num, Utility.getReturnCode(returnCode));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 邮箱发送验证码
	 * @param email
	 */
	@ResponseBody
	@RequestMapping(value = "/sendEmailCode", method = RequestMethod.POST)
	public void sendEmailCode(String email){
		try {
			if(ToolUtil.isEmpty(email)) {
				error("邮箱地址为空");
				return;
			}
			String emailCode = RandomUtil.randomCode();
			session.setAttribute(SubjectAttrConstants.SESSION_EMAIL_CODE, emailCode);
			SendEmail.sendEmailCode(email, emailCode);
			success("邮箱验证码发送成功");
		} catch (Exception e) {
			error("邮箱验证码发送失败");
		}
	}

	private void checkPhone(String phone) {
		if (ToolUtil.isEmpty(phone)) {
			error("手机号码为空!");
			return;
		}

		if (!Utility.isMobileNO(phone)) {
			error("手机号码格式不正确!");
			return;
		}
	}
	
	private void saveInvitation(String code, int userId){
		//邀请成员注册填写邀请码
		if(ToolUtil.isNotEmpty(code)){
			Invitation invitation = invitationService.findInvitationByCode(code);
			if(null != invitation) {
				invitation.setReceiveId(userId);
				invitation.setSendStatus(2);
				invitation.setAcceptTime(Utility.getSimpleFormatedDayNow());
				invitationService.updateInvitation(invitation);
				userRoleService.saveUserRole(new UserRole(userId, invitation.getRoleId(), invitation.getInviteId()));
			}
		}
	}
}
